import React, { useState, useEffect } from 'react';
import { Button, Form, Input, Select, Table, Modal, message, Image } from 'antd';
import { advertisementList, adtype, advertisementAdd, advertisementDelete } from '../../apis/advertisement';
import UpPhoto from "../../components/UpPhoto";
import { ExclamationCircleFilled } from '@ant-design/icons';
import '../../assets/scss/advertisement.scss'

// 图片根路径
const IMG_URL = process.env.REACT_APP_IMG_URL;
const layout = {
	labelCol: { span: 6 },
};
const Advertisement = (): JSX.Element => {

	//提示
	const [messageApi, contextHolder] = message.useMessage();
	//表格
	const columns: any = [
		{
			title: 'id',
			dataIndex: 'id',
			align: 'center'
		},
		{
			title: '标题',
			dataIndex: 'title',
			align: 'center'
		},
		{
			title: '图片',
			dataIndex: 'picture',
			key: 'picture',
			render: (text: any) => (
				<Image width={50} height={50} src={IMG_URL + text} alt="" />
			)
		},
		{
			title: '类型',
			dataIndex: 'typeName',
			align: 'center'
		},
		{
			title: '状态',
			dataIndex: 'sort',
			align: 'center'
		},
		{
			title: '操作',
			align: 'center',
			render: (params: any) =>
				<div>
					<Button type="primary" style={{ marginLeft: '10px', backgroundColor: "#67c23a" }} onClick={() => { showModal(params) }}>编辑 </Button>
					<Button type="primary" danger style={{ marginLeft: '10px' }} onClick={() => { delhouse(params.id) }}>删除</Button>
				</div>
		}
	];


	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
		console.log('selectedRowKeys changed: ', newSelectedRowKeys);
		setSelectedRowKeys(newSelectedRowKeys);
	};

	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};
	const hasSelected = selectedRowKeys.length > 0;

	const administrator = { typeid: 1, page: 1, psize: 100000 }
	const [list, setlist] = useState()
	//获取广告图片管理
	const AdvertisementList = async () => {
		const res: any = await advertisementList(administrator);
		console.log(999999999, res);
		if (res.errCode == 10000) {
			setlist(res.data.list)
		}
	}
	//添加
	const [form] = Form.useForm();
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [id, setID] = useState(0);
	const [picturehui, setPicturehui] = useState();

	const showModal = (params: any) => {

		console.log(9923, params);
		setID(params.id);
		setPicturehui(params.picture)
		setIsModalOpen(true);

		useAddRoom({ ...addRoom, picture: params.picture })
		if (params.id > 0) {
			form.setFieldsValue({
				title: params.title,
				sort: params.sort,
				typeid: params.typeid,
				url: params.url,
				enabled: params.enabled,
				// picture: params.picture,
			})
		}
	};
	//添加确定按钮
	const [addRoom, useAddRoom] = useState<any>({ picture: '' })
	const handleOk = async (value: any) => {
		// console.log(999, value);
		// console.log(999, addRoom);

		const res: any = await advertisementAdd({ ...value, id, picture: addRoom.picture });
		console.log(res);
		if (res.errCode == 10000) {
			setIsModalOpen(false);
			AdvertisementList()
			form.setFieldsValue({
				title: '',
				typeid: '',
				url: '',
				name: '',
				// picture: '',
				sort: '',
				enabled: '',
			})
			//添加成功提示
			if (id > 0) {
				messageApi.open({
					type: 'success',
					content: '编辑成功！',
					duration: 10,
				});
			} else {
				messageApi.open({
					type: 'success',
					content: '添加成功！',
					duration: 10,
				});
			}
		}
	};
	//关闭添加弹出框
	const handleCancel = () => {
		setIsModalOpen(false);
		form.setFieldsValue({
			title: '',
			typeid: '',
			url: '',
			name: '',
			// picture: '',
			sort: '',
			enabled: '',
		})
	};
	//图片位置管理
	const [adtypeList, setAdtypeList] = useState<any>([]);
	const AdtypeList = async () => {
		const res: any = await adtype({ page: 1, psize: 100 });
		console.log(2222222, res);
		if (res.errCode == 10000) {
			setAdtypeList(res.data.list)
		}
	}
	//查询
	const onFinish = async (values: any) => {
		console.log(values);
		//获取广告图片管理
		const res: any = await advertisementList({ typeid: values.typeid, page: 1, psize: 1000 });
		console.log(999999999, res);
		if (res.errCode == 10000) {
			setlist(res.data.list)
		}
	};
	//删除
	const { confirm } = Modal;
	const delhouse = async (e: any) => {
		confirm({
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content: '确定删除',
			async onOk() {
				const res: any = await advertisementDelete({ id: e });
				console.log(7777777777777, res);
				if (res.errCode == 10000) {
					AdvertisementList()
					//删除成功提示
					messageApi.open({
						type: 'success',
						content: '删除成功！',
						duration: 10,
					});
				}
			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}
	//封装的图片
	const handleChildButtonClick = (message: any) => {
		console.log(message);
		useAddRoom({ ...addRoom, picture: message })
	};
	useEffect(() => {
		console.log("页面挂载完成");
		AdvertisementList()
		AdtypeList()
	}, [])
	return (
		<div className='advertisement'>
			{/* <div style={{ padding: '10px', color: '#4180f3' }}></div> */}
			<div className='hd'>
				<div className='title'>图片管理</div>
			</div>
			<div className='bd'>
				<div>
					<Form
						name="basic2"
						style={{ display: 'flex' }}
						initialValues={{ remember: true }}
						onFinish={onFinish}
						autoComplete="off"
					>
						<Form.Item
							label="类型"
							name="typeid"
							style={{ width: '200px' }}
						>
							<Select fieldNames={{ label: "name", value: "id" }} options={adtypeList} placeholder='APP轮播图片' />
						</Form.Item>
						<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
							<Button type="primary" htmlType="submit">
								查询
							</Button>
						</Form.Item>
					</Form>
					{/* 添加 */}
					<Button type="primary" onClick={() => showModal({ id: 0 })}>添加</Button>
				</div>
				<div>
					{/* 提示消息 */}
					{contextHolder}
					<div style={{ marginBottom: 16 }}>
						<span style={{ marginLeft: 8 }}>
							{hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
						</span>
					</div>
					<Table rowSelection={rowSelection} columns={columns} dataSource={list} bordered rowKey={(columns) => columns.id} />
				</div>
			</div>
			<div style={{ width: '100%', padding: '10px' }}>
				<div>
					<Modal title={id == 0 ? <div>添加</div> : <div>编辑</div>} open={isModalOpen} onCancel={handleCancel} destroyOnClose={true} onOk={handleOk} footer={null}>
						<Form
							{...layout}
							name="basic"
							form={form}
							onFinish={handleOk}
							style={{ maxWidth: 420 }}
							autoComplete="off"
						>
							<Form.Item
								label="标题:"
								name="title"
								rules={[{ required: true, message: 'Please input your username!' }]}
							>
								<Input />
							</Form.Item>
							<Form.Item
								label="位置:"
								name="typeid"
								rules={[{ required: true, message: 'Please input your username!' }]}
							>
								<Select fieldNames={{ label: "name", value: "id" }} options={adtypeList} placeholder='APP轮播图片' />
							</Form.Item>
							<Form.Item
								label="URL:"
								name="url"
							>
								<Input />
							</Form.Item>
							<Form.Item
								label="图片:"
								name="picture"
							>
								<UpPhoto picture={picturehui} onButtonClick={handleChildButtonClick}></UpPhoto>
							</Form.Item>
							{/* <Form.Item label="图片:" name="picture">
								<Upload
									name="avatar"
									listType="picture-card"
									className="avatar-uploader"
									showUploadList={false}
									action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
									beforeUpload={beforeUpload}
									onChange={handleChange}
								>
									{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
								</Upload>
							</Form.Item> */}
							<Form.Item
								label="排序:"
								name="sort"
								rules={[{ required: true, message: 'Please input your username!' }]}
							>
								<Input />
							</Form.Item>
							<Form.Item
								label="是否显示:"
								name="enabled"
								rules={[{ required: true, message: 'Please input your username!' }]}
							>
								<Select>
									<Select.Option value="1">显示</Select.Option>
									<Select.Option value="0">隐藏</Select.Option>
								</Select>
								{/* <Cascader fieldNames={{ label: "name", value: "id" }} options={residences} /> */}
							</Form.Item>
							<Form.Item style={{ marginLeft: '1.88rem' }}>
								<Button type="primary" htmlType="submit">
									提交
								</Button>
								<Button onClick={() => handleCancel()} style={{ marginLeft: '.1rem' }}>
									取消
								</Button>
							</Form.Item>
						</Form>
					</Modal>
				</div>
			</div>
		</div>
	)
};

export default Advertisement;